<template>
  <div class="share-list">
    <!-- 批量操作工具栏 -->
    <div v-if="selectedShares.length > 0" class="batch-toolbar">
      <div class="batch-info">
        {{ t('share.list.batchSelected', { count: selectedShares.length }) }}
      </div>
      <div class="batch-actions">
        <el-button size="small" @click="handleBatchEnable">{{ t('share.list.batchEnable') }}</el-button>
        <el-button size="small" @click="handleBatchDisable">{{ t('share.list.batchDisable') }}</el-button>
        <el-button size="small" type="danger" @click="handleBatchDelete">{{ t('share.list.batchDelete') }}</el-button>
        <el-button size="small" @click="clearSelection">{{ t('share.list.cancelSelection') }}</el-button>
      </div>
    </div>

    <div class="table-container">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="shares"
        style="width: 100%"
        table-layout="auto"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column :label="t('share.list.columns.fileName')" min-width="200">
          <template #default="{ row }">
            <div class="file-name">
              <el-icon><Document /></el-icon>
              <span class="name">{{ row.fileName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="t('share.list.columns.shareLink')" min-width="200" :class-name="isMobile ? 'hide-on-mobile' : ''">
          <template #default="{ row }">
            <div class="share-link">
              <el-tag size="small" :type="row.shareType === 'PASSWORD' ? 'warning' : 'info'">
                {{ row.shareType === 'PASSWORD' ? t('share.list.shareTypes.password') : t('share.list.shareTypes.public') }}
              </el-tag>
              <div class="link-actions">
                <el-button size="small" type="primary" link @click="copyShareLink(row)">
                  <el-icon><CopyDocument /></el-icon>
                  {{ t('share.list.actions.copy') }}
                </el-button>
                <el-button size="small" type="success" link @click="showQRCode(row)">
                  <el-icon><Picture /></el-icon>
                  {{ t('share.list.actions.qrcode') }}
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="t('share.list.columns.description')" min-width="150" :class-name="isMobile ? 'hide-on-mobile' : ''">
          <template #default="{ row }">
            <div class="share-description">
              <span v-if="row.description" class="description-text">{{ row.description }}</span>
              <span v-else class="no-description">{{ t('share.list.noDescription') }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="t('share.list.columns.accessCount')" width="100" align="center" :class-name="isMobile ? 'hide-on-mobile' : ''">
          <template #default="{ row }">
            <span>{{ row.accessCount }}</span>
            <span v-if="row.maxAccessCount" class="access-limit">/{{ row.maxAccessCount }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="t('share.list.columns.expiryTime')" width="180" :class-name="isMobile ? 'hide-on-mobile' : ''">
          <template #default="{ row }">
            <span v-if="row.expireTime">{{ row.expireTime }}</span>
            <span v-else>{{ t('share.list.expiryTime.permanent') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="t('share.list.columns.status')" width="100" align="center">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row)"
              size="small"
            >
              {{ getStatusText(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="t('share.list.columns.actions')" width="180" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                v-if="row.status === 'ACTIVE'"
                type="danger"
                link
                @click="handleDisable(row)"
              >
                {{ t('share.list.actions.disable') }}
              </el-button>
              <el-button
                v-if="row.status === 'DISABLED'"
                type="success"
                link
                @click="handleEnable(row)"
              >
                {{ t('share.list.actions.enable') }}
              </el-button>
              <el-button type="primary" link @click="handleEdit(row)">{{ t('share.list.actions.edit') }}</el-button>
              <el-popconfirm
                :title="t('share.messages.deleteConfirm')"
                @confirm="handleDelete(row)"
              >
                <template #reference>
                  <el-button type="danger" link>{{ t('share.list.actions.delete') }}</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="mobile-actions" v-if="isMobile">
        <el-dropdown v-for="row in shares" :key="row.id" trigger="click">
          <div class="mobile-row">
            <div class="file-info">
              <div class="file-name">
                <el-icon><Document /></el-icon>
                <span class="name">{{ row.fileName }}</span>
              </div>
              <div v-if="row.description" class="mobile-description">
                <span class="description-text">{{ row.description }}</span>
              </div>
            </div>
            <el-tag
              :type="getStatusType(row)"
              size="small"
              class="status-tag"
            >
              {{ getStatusText(row) }}
            </el-tag>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="copyShareLink(row)">
                <el-icon><CopyDocument /></el-icon>{{ t('share.list.actions.copy') }}
              </el-dropdown-item>
              <el-dropdown-item @click="showQRCode(row)">
                <el-icon><Picture /></el-icon>{{ t('share.list.actions.qrcode') }}
              </el-dropdown-item>
              <el-dropdown-item v-if="row.status === 'ACTIVE'" @click="handleDisable(row)">
                <el-icon><Lock /></el-icon>{{ t('share.list.actions.disable') }}
              </el-dropdown-item>
              <el-dropdown-item v-if="row.status === 'DISABLED'" @click="handleEnable(row)">
                <el-icon><Unlock /></el-icon>{{ t('share.list.actions.enable') }}
              </el-dropdown-item>
              <el-dropdown-item @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>{{ t('share.list.actions.edit') }}
              </el-dropdown-item>
              <el-dropdown-item divided @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>{{ t('share.list.actions.delete') }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          :layout="isMobile ? 'prev, pager, next' : 'total, sizes, prev, pager, next'"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 二维码对话框 -->
    <el-dialog
      v-model="qrCodeVisible"
      :title="t('share.qrCode.title')"
      width="400px"
      align-center
    >
      <div class="qr-code-container">
        <div class="qr-code">
          <!-- 加载状态 -->
          <div v-if="qrCodeLoading" class="qr-code-loading">
            <el-icon class="is-loading"><Loading /></el-icon>
            <p>{{ t('share.qrCode.generating') }}</p>
          </div>
          <!-- 二维码显示 -->
          <div v-else-if="qrCodeDataUrl" class="qr-code-display">
            <img
              :src="qrCodeDataUrl"
              :alt="t('share.qrCode.title')"
              class="qr-code-image"
              @error="handleQRCodeError"
            />
          </div>
          <!-- 错误状态 -->
          <div v-else class="qr-code-error">
            <el-icon><Warning /></el-icon>
            <p>{{ t('share.qrCode.generateFailed') }}</p>
            <el-button size="small" @click="retryQRCode">{{ t('share.qrCode.retry') }}</el-button>
          </div>
        </div>
        <div class="share-info">
          <p><strong>{{ t('share.qrCode.fileName') }}</strong>{{ currentShare?.fileName }}</p>
          <p><strong>{{ t('share.qrCode.shareLink') }}</strong></p>
          <el-input
            :value="currentShareUrl"
            readonly
            class="share-url-input"
          >
            <template #append>
              <el-button @click="copyShareLink(currentShare!)">{{ t('share.qrCode.copy') }}</el-button>
            </template>
          </el-input>
        </div>
      </div>
    </el-dialog>

    <!-- 分享详情抽屉 -->
    <ShareDetailDrawer ref="detailDrawerRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, watch } from 'vue'
import { Document, CopyDocument, Edit, Delete, Lock, Unlock, Picture, Loading, Warning } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { storeToRefs } from 'pinia'
import { useShareStore } from '@/stores/shareStore'
import type { ShareInfo } from '@/types/share'
import ShareDetailDrawer from './ShareDetailDrawer.vue'
import { useQRCode } from '@vueuse/integrations/useQRCode'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

const shareStore = useShareStore()
const { shares, loading, pagination } = storeToRefs(shareStore)
const detailDrawerRef = ref<InstanceType<typeof ShareDetailDrawer>>()

// 二维码相关状态
const qrCodeVisible = ref(false)
const currentShare = ref<ShareInfo | null>(null)
const qrCodeRef = ref<HTMLElement>()
const qrCodeLoading = ref(false)

// 批量操作相关状态
const selectedShares = ref<ShareInfo[]>([])
const tableRef = ref()

const currentShareUrl = computed(() => {
  if (!currentShare.value) return ''
  const baseUrl = window.location.origin
  return `${baseUrl}/s/${currentShare.value.shareCode}`
})

// 使用VueUse的useQRCode生成二维码
const qrCodeDataUrl = useQRCode(currentShareUrl)

const isMobile = computed(() => {
  return window.innerWidth <= 768
})

const getStatusType = (share: ShareInfo) => {
  // 优先检查是否过期
  if (share.expired) {
    return 'warning'
  }

  const map: Record<string, string> = {
    ACTIVE: 'success',
    DISABLED: 'danger',
    EXPIRED: 'warning'
  }
  return map[share.status] || 'info'
}

const getStatusText = (share: ShareInfo) => {
  // 优先检查是否过期
  if (share.expired) {
    return t('share.list.status.expired')
  }

  const statusMap: Record<string, string> = {
    ACTIVE: 'active',
    DISABLED: 'disabled',
    EXPIRED: 'expired'
  }
  const statusKey = statusMap[share.status]
  return statusKey ? t(`share.list.status.${statusKey}`) : share.status
}

const copyShareLink = async (share: ShareInfo) => {
  const baseUrl = window.location.origin
  const shareUrl = `${baseUrl}/s/${share.shareCode}`
  try {
    await navigator.clipboard.writeText(shareUrl)
    ElMessage.success('分享链接已复制')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

const handleSizeChange = () => {
  shareStore.fetchShareList()
}

const handleCurrentChange = () => {
  shareStore.fetchShareList()
}

const handleDisable = async (share: ShareInfo) => {
  const result = await shareStore.disableShare(share.id)
  if (result.success) {
    ElMessage.success(result.message)
  } else {
    ElMessage.error(result.message)
  }
}

const handleEnable = async (share: ShareInfo) => {
  const result = await shareStore.enableShare(share.id)
  if (result.success) {
    ElMessage.success(result.message)
  } else {
    ElMessage.error(result.message)
  }
}

const handleEdit = (share: ShareInfo) => {
  detailDrawerRef.value?.open(share)
}

const handleDelete = async (share: ShareInfo) => {
  const result = await shareStore.deleteShare(share.id)
  if (result.success) {
    ElMessage.success(result.message)
  } else {
    ElMessage.error(result.message)
  }
}

const showQRCode = async (share: ShareInfo) => {
  currentShare.value = share
  qrCodeVisible.value = true
  qrCodeLoading.value = true

  await nextTick()

  // 等待二维码生成完成
  watch(qrCodeDataUrl, (newValue) => {
    if (newValue) {
      qrCodeLoading.value = false
    }
  }, { immediate: true })
}

// 二维码错误处理
const handleQRCodeError = () => {
  ElMessage.error('二维码加载失败')
  qrCodeLoading.value = false
}

// 重试生成二维码
const retryQRCode = () => {
  qrCodeLoading.value = true
  // 重新触发二维码生成
  const share = currentShare.value
  if (share) {
    currentShare.value = null
    nextTick(() => {
      currentShare.value = share
    })
  }
}

// 批量操作相关方法
const handleSelectionChange = (selection: ShareInfo[]) => {
  selectedShares.value = selection
}

const clearSelection = () => {
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
  selectedShares.value = []
}

const handleBatchEnable = async () => {
  if (selectedShares.value.length === 0) return

  try {
    const promises = selectedShares.value.map(share => shareStore.enableShare(share.id))
    await Promise.all(promises)
    ElMessage.success(`成功启用 ${selectedShares.value.length} 个分享`)
    clearSelection()
  } catch (error) {
    ElMessage.error('批量启用失败')
  }
}

const handleBatchDisable = async () => {
  if (selectedShares.value.length === 0) return

  try {
    const promises = selectedShares.value.map(share => shareStore.disableShare(share.id))
    await Promise.all(promises)
    ElMessage.success(`成功禁用 ${selectedShares.value.length} 个分享`)
    clearSelection()
  } catch (error) {
    ElMessage.error('批量禁用失败')
  }
}

const handleBatchDelete = async () => {
  if (selectedShares.value.length === 0) return

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedShares.value.length} 个分享吗？此操作不可恢复。`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const promises = selectedShares.value.map(share => shareStore.deleteShare(share.id))
    await Promise.all(promises)
    ElMessage.success(`成功删除 ${selectedShares.value.length} 个分享`)
    clearSelection()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}
</script>

<style lang="scss">
@import '@/styles/index.scss';

.share-list {
  flex: 1;
  min-width: 0;
  background-color: var(--el-bg-color);
  border-radius: 4px;
  padding: 16px;
  box-sizing: border-box;

  @include respond-to('lg') {
    padding: 12px;
  }

  .file-name {
    @include flex-start;
    gap: 8px;

    .name {
      @include text-ellipsis;
    }
  }

  .share-link {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .link-actions {
      @include flex-start;
      gap: 8px;
      flex-wrap: wrap;
    }

    @include respond-to('lg') {
      gap: 6px;
    }
  }

  .access-limit {
    color: var(--el-text-color-secondary);
  }

  .share-description {
    .description-text {
      color: var(--el-text-color-regular);
      font-size: 14px;
      line-height: 1.4;
      @include text-ellipsis;
      max-width: 200px;
    }

    .no-description {
      color: var(--el-text-color-placeholder);
      font-size: 12px;
      font-style: italic;
    }
  }

  .action-buttons {
    @include flex-start;
    gap: 8px;
    flex-wrap: wrap;
  }

  .mobile-actions {
    display: none;

    @include respond-to('md') {
      display: block;
    }

    .mobile-row {
      @include flex-between;
      padding: 12px;
      border-bottom: 1px solid var(--el-border-color-light);
      cursor: pointer;

      &:hover {
        background-color: var(--el-fill-color-light);
      }

      .file-info {
        flex: 1;
        min-width: 0;

        .file-name {
          @include flex-start;
          gap: 8px;
          margin-bottom: 4px;

          .name {
            @include text-ellipsis;
          }
        }

        .mobile-description {
          .description-text {
            color: var(--el-text-color-secondary);
            font-size: 12px;
            line-height: 1.3;
            @include text-ellipsis;
          }
        }
      }

      .status-tag {
        margin-left: 8px;
        flex-shrink: 0;
      }
    }
  }

  :deep(.hide-on-mobile) {
    @include respond-to('md') {
      display: none;
    }
  }

  :deep(.el-table) {
    @include respond-to('md') {
      display: none;
    }
  }

  .pagination {
    margin-top: 16px;
    @include flex-center;

    @include respond-to('lg') {
      margin-top: 12px;
    }
  }
}

.qr-code-container {
  text-align: center;

  .qr-code {
    margin-bottom: 20px;
    padding: 20px;
    background-color: var(--el-fill-color-lighter);
    border-radius: 8px;
    min-height: 240px;
    display: flex;
    align-items: center;
    justify-content: center;

    .qr-code-loading {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 12px;
      color: var(--el-text-color-regular);

      .el-icon {
        font-size: 24px;
        color: var(--el-color-primary);
      }

      p {
        margin: 0;
        font-size: 14px;
      }
    }

    .qr-code-display {
      .qr-code-image {
        width: 200px;
        height: 200px;
        display: block;
        margin: 0 auto;
        border-radius: 4px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }

    .qr-code-error {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 12px;
      color: var(--el-color-danger);

      .el-icon {
        font-size: 24px;
      }

      p {
        margin: 0;
        font-size: 14px;
        color: var(--el-text-color-regular);
      }
    }
  }

  .share-info {
    text-align: left;

    p {
      margin: 8px 0;
      color: var(--el-text-color-regular);
    }

    .share-url-input {
      margin-top: 8px;
    }
  }
}

.batch-toolbar {
  @include flex-between;
  padding: 12px 16px;
  margin-bottom: 16px;
  background-color: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-7);
  border-radius: 6px;

  .batch-info {
    color: var(--el-color-primary);
    font-weight: 500;
  }

  .batch-actions {
    @include flex-center;
    gap: 8px;
  }

  @include respond-to('sm') {
    flex-direction: column;
    gap: 12px;

    .batch-actions {
      width: 100%;
      justify-content: space-between;

      .el-button {
        flex: 1;
      }
    }
  }
}
</style>